package com.itheima.stock.mq;

import com.github.benmanes.caffeine.cache.Cache;
import com.itheima.stock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class MqListener {
    @Autowired
    private Cache<String,Object> caffeineCache;
    @Autowired
    private StockService stockService;

    @RabbitListener(queues = {"innerMarketQueue"})
    public void acceptInnerMarketInfo(Date date)throws Exception{
        long diffTime = DateTime.now().getMillis() - new DateTime(date).getMillis();
        if(diffTime>60000){
            log.error("采集国内大盘时间点：{},同步超时：{}ms",new DateTime(date).toString("yyyy-MM-dd HH:mm:ss"),diffTime);
        }
        //将缓存置为失效删除
        caffeineCache.invalidate("innerMarketInfosKey");
        //调用服务更新缓存
        stockService.getNewestInnerMarketInfos();
    }

    @RabbitListener(queues = "stockRtQueue")
    public void acceptStockRtQueue(Date date){
        long diffTime = DateTime.now().getMillis() - new DateTime(date).getMillis();
        if(diffTime>60000){
            log.error("采集国内个股时间点：{},同步超时：{}ms",new DateTime(date).toString("yyyy-MM-dd HH:mm:ss"),diffTime);
        }

        caffeineCache.invalidate("stockRtInfosKey");
        stockService.getNewestStockRtInfos();
    }

    @RabbitListener(queues = "blockRtQueue")
    public void acceptBlockRtQueue(Date date){
        long diffTime = DateTime.now().getMillis() - new DateTime(date).getMillis();
        if(diffTime>60000){
            log.error("采集国内板块时间点：{},同步超时：{}ms",new DateTime(date).toString("yyyy-MM-dd HH:mm:ss"),diffTime);
        }

        caffeineCache.invalidate("blockRtInfosKey");
        stockService.getNewestBlockRtInfos();
    }
    @RabbitListener(queues = "outerMarketQueue")
    public void acceptOuterMarketInfo(Date date)throws Exception{
        long diffTime = DateTime.now().getMillis() - new DateTime(date).getMillis();
        if(diffTime>60000){
            log.error("采集国外大盘时间点：{},同步超时：{}ms",new DateTime(date).toString("yyyy-MM-dd HH:mm:ss"),diffTime);
        }
        caffeineCache.invalidate("outerMarketInfosKey");
        stockService.getNewestOuterMarketInfos();
    }
}
